<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="formVisible=true">
          创建伴学室
        </el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="督学室名称" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%" border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key" @sort-change="tableSortCge">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="name" label="伴学室名称"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="teacherName" label="责任伴学师"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="student_num" label="学员数"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="remind_time" label="教师提醒">
        <template slot-scope="scope">
          <span v-if="scope.row.remind_time==0">不提醒</span>
          <span v-else>提前{{ scope.row.remind_time }}分钟</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="class_hour" label="常规课时时长">
        <template slot-scope="scope">
          <span>{{ scope.row.class_hour[0] }}</span>
          <br>
          <span>{{ scope.row.class_hour[1] }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="class_count" label="课时数"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="effective_day_num" label="生效天数"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="isEffective" label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.isEffective==1">有效期</span>
          <span v-else>过期</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="100" align="center" prop="create_time" label="创建日期"></el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openEdit(scope.row)">编辑
            </el-button>
            <el-button size="mini" type="primary" @click="showDetail(scope.row)">查看</el-button>
            <el-button size="mini" type="primary" @click="onlineAcc(scope.row)">在线伴学</el-button>
            <el-button size="mini" @click="delContent(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText"/>

    <el-dialog :title="editSubjects ? '编辑伴学室': '创建伴学室'" :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px">
        <el-form-item label="伴学室名称:" label-width="130px" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入伴学室名称"></el-input>
        </el-form-item>
        <el-form-item label="责任伴学师:" label-width="130px" prop="sup_teacher">
          <el-select v-model="addForm.sup_teacher" filterable placeholder="请选择责任伴学师">
            <el-option
              v-for="item in teacherArr"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="常规伴学时间:" label-width="130px" prop="class_hour">
          <el-time-picker
            is-range
            v-model="addForm.class_hour"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            :default-value="value1"
            value-format="HH:mm:ss">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="课时数量:" label-width="130px" prop="class_count">
          <el-select v-model="addForm.class_count" placeholder="请选择">
            <el-option
              v-for="item in classCountOption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生弹窗确认:" label-width="130px" prop="open_window">
          <el-radio-group v-model="addForm.open_window">
            <el-radio :label="1">需要</el-radio>
            <el-radio :label="-1">不需要</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="添加方式:" label-width="130px">
          <el-radio-group v-model="addForm.addType">
            <el-radio :label="1">选择添加</el-radio>
            <el-radio :label="2">批量导入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学生账号:" label-width="130px" prop="account">
          <el-select v-model="addForm.account" multiple filterable placeholder="请选择学生">
            <el-option
              v-for="item in studentArr"
              :key="item.id"
              :label="item.account"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期:" label-width="130px" prop="effective_days">
          <el-date-picker
            type="dates"
            v-model="addForm.effective_days"
            placeholder="选择一个或多个日期"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="教师提醒时间:" label-width="130px" prop="remind_time">
          <el-select v-model="addForm.remind_time" placeholder="请选择">
            <el-option
              v-for="item in remindOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="editClassroomControl('ruleForm')" size="mini" round>确定
        </el-button>
        <el-button v-else type="primary" @click="addClassroomControl('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import objectable from "@/utils/objectable.js";
import dynamicTable from "@/components/DynamicTable/index";
import deleteDialog from "@/components/deleteDialog/index";
import tableMini from '@/utils/tableMini.js'
import permission from "@/directive/permission";
import {
  addClassroom, delClassroom,
  editClassroom,
  getStudent,
  getSupAndAccTeacher, queryClassroom,
} from "@/api/teacher";

export default {
  mixins: [tableMini],
  components: {dynamicTable, deleteDialog},
  directives: {permission},
  data() {
    return {
      key: 1,
      colData: [], //动态控制table
      checkboxVal: ["ID", "伴学室名称", "责任伴学师", "学员数", "教师提醒", "常规课时时长", "课时数", "生效天数", "状态", "创建日期"],
      searchTable: "",
      select: "", //搜索条件
      tableData: [],
      listQuery: {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
        type: 2
      },
      addForm: {
        name: '',
        sup_teacher: '',
        open_window: -1,
        class_hour: 0,
        class_count: 1,
        addType: 1,
        account: [],
        effective_days: [],
        remind_time: 0,
      },
      formVisible: false,
      rules: {
        name: [{required: true, message: '请输入督学室名称', trigger: 'blur'}],
        sup_teacher: [{required: true, message: '请选择责任督学师', trigger: 'change'}],
        class_hour: [{required: true, message: '请选择督学时间', trigger: 'change'}],
        class_count: [{required: true, message: '请设置课时数量', trigger: 'change'}],
        open_window: [{required: true, message: '请选择是否需要平板端弹窗确认', trigger: 'blur'}],
        account: [{required: true, message: '请选择学生账号', trigger: 'change'}],
        effective_days: [{required: true, message: '请选择有效期', trigger: 'change'}],
        remind_time: [{required: true, message: '请选择教师提醒时间', trigger: 'change'}],
      },
      editSubjects: false,
      deleteDialogs: {show: false, deleteText: '', deleteId: 0},
      batchArr: [],
      agentArr: [],
      dialogVisible: false,
      teacherArr: [],
      studentArr: [],
      value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
      classCountOption: [
        {label: '1', value: 1},
        {label: '1.5', value: 1.5},
        {label: '2', value: 2},
        {label: '2.5', value: 2.5},
        {label: '3', value: 3},
        {label: '3.5', value: 3.5},
        {label: '4', value: 4},
        {label: '4.5', value: 4.5},
        {label: '5', value: 5}],
      remindOptions: [{label: '不提醒', value: 0},
        {label: '提前15分钟', value: 15},
        {label: '提前30分钟', value: 30},
        {label: '提前1小时', value: 60}],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 86400000
        }
      },

    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getAccountLimit()
    this.getSupAndAccTeacherControl()
    this.getStudentControl()

  },
  methods: {
    Refresh() {
      this.listQuery = {startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 2}
      this.getAccountLimit()
    },
    getSupAndAccTeacherControl() {
      getSupAndAccTeacher({userId: localStorage.getItem("ID")}).then(res => {
        this.teacherArr = res.data
      }).catch(err => {
        this.teacherArr = []
      })
    },
    getStudentControl() {
      getStudent({userId: localStorage.getItem("ID")}).then(res => {
        this.studentArr = res.data
      }).catch(err => {
        this.studentArr = []
      })
    },
    //搜索
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.agentName = this.searchTable
          this.getAccountLimit();
          break;
      }
    },
    openEdit(row) {
      this.formVisible = true
      this.editSubjects = true
      this.addForm = {
        name: row.name,
        sup_teacher: row.teacher_id,
        open_window: row.open_window,
        class_hour: row.class_hour,
        class_count: row.class_count,
        addType: 1,
        account: row.account,
        effective_days: row.effective_days,
        remind_time: row.remind_time,
        id: row.id
      }
    },
    editClassroomControl(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let editForm = JSON.parse(JSON.stringify(this.addForm))
          editForm.last_ip = sessionStorage.getItem("Ip")
          editForm.userId = localStorage.getItem("ID")
          editForm.type = 2
          editClassroom(editForm).then(res => {
            this.$message.success(res.msg)
            this.getAccountLimit()
            this.formVisible = false
            this.editSubjects = false
          }).catch(err => {
          })
        } else {
          return false;
        }
      });
    },
    addClassroomControl(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.type = 2
          addClassroom(addForm).then(res => {
            this.$message.success(res.msg)
            this.getAccountLimit()
            this.formVisible = false
          }).catch(err => {
          })
        } else {
          return false;
        }
      });
    },
    getAccountLimit() {
      queryClassroom(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    delContent(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    showDetail(row) {
      this.$router.push({name: 'student', query: {roomID: row.id}});
    },
    onlineAcc(row) {
      this.$router.push({name: 'accOnline', query: {roomId: row.id, name: row.name, student_num:row.student_num, create_time:row.create_time, teacherId:row.teacher_id}});
    },
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId,
      }
      delClassroom(params).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
        this.getAccountLimit()
      }).catch(err => {
        console.log("请求失败", err)
      })
    },
    //分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getAccountLimit()
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getAccountLimit()
    },
    //表格排序事件
    tableSortCge(column) {
      let order = ''
      column.order == "descending" ? order = 'desc' : order = 'asc'
      let sort = [{field: column.prop, sort: order}]
      this.listQuery.sort = JSON.stringify(sort)
      this.getAccountLimit()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.editSubjects = false
      this.$nextTick(() => {
        this.addForm = this.$options.data().addForm
      })
    },
  }
}
</script>

<style scoped>

</style>


